﻿using ComTools.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;

namespace MSSQL.CommandTool
{
	/// <summary>
	/// 数据库配置操作对象
	/// </summary>
	public class DatabaseManager
	{
		#region 变量
		/// <summary>
		/// 数据库配置文件路径
		/// </summary>
		private static string databaseConfigPath;

		/// <summary>
		/// 数据库实例配置
		/// </summary>
		private static Dictionary<string, DatabaseInstance> databaseInstanceDictionary;

		/// <summary>
		/// 侦听文件系统对象
		/// </summary>
		private static FileSystemWatcher sWatcher = new FileSystemWatcher()
		{
			NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite
		};

		/// <summary>
		/// 同步锁对象
		/// </summary>
		private static readonly object locker = new object();

		/// <summary>
		/// 数据库配置文件
		/// </summary>
		private const string dbConfigFilePath = @"CommandTool\DataBaseConfig\Database.config";
		#endregion

		static DatabaseManager()
		{
			try {
				string rootDic = string.Empty;

				try {
					rootDic = HttpRuntime.BinDirectory;
				} catch {
					rootDic = AppDomain.CurrentDomain.BaseDirectory;
				}
				databaseConfigPath = $"{rootDic}{dbConfigFilePath}";
				sWatcher.Changed += (s, e) => { InitDatabaseList(); };
				sWatcher.Path = Path.GetDirectoryName(databaseConfigPath);
				InitDatabaseList();
				sWatcher.EnableRaisingEvents = true;
			}
			catch (Exception ex) {
				throw ex;
			}
		}

		/// <summary>
		/// 获取数据库配置实例
		/// </summary>
		/// <param name="name"></param>
		/// <returns>处理结果</returns>
		public static DatabaseInstance GetDatabase(string name)
		{
			return databaseInstanceDictionary[name];
		}

		/// <summary>
		/// 初始化数据库配置集合
		/// </summary>
		private static void InitDatabaseList()
		{
			lock (locker)
			{
				try {
					databaseInstanceDictionary = new Dictionary<string, DatabaseInstance>();
					Databases databases = XmlEntitySerializer.DeserilizeFromXml<Databases>(databaseConfigPath);
					foreach (DatabaseGroup group in databases.GroupList)
					{
						foreach (DatabaseInstance instance in group.InstanceList)
						{
							databaseInstanceDictionary.Add(instance.Name, instance);
						}
					}
				}
				catch (Exception ex) {
					throw ex;
				}
			}
		}
	}
}
